<script setup>
import { onMounted, ref } from 'vue'
import { Delete, Edit, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { blogList, insertBlog, updateBlog, deleteBlog, classList } from '@/api/blog'
import dayjs from 'dayjs'

const formRef = ref() 
const pageNo   = ref(1)
const total    = ref(0)
const pageSize = ref(5)

const searchParams = ref({
  title: '',
  classid: '',
  authorname: '',
  isfeatured: ''
})

const blogListData = ref([])
const classListData = ref([])
const userListData = ref([])

const drawerVisible = ref(false)
const isEdit = ref(false)
const formModel = ref({
  id: '',
  title: '',
  content: '',
  excerpt: '',
  coverimage: '',
  classid: '',
  authorid: '',
  isfeatured: 0,
  iscommentable: 1,
  metatitle: '',
  metadescription: '',
  metakeywords: '',
  publishedat: ''
})

const resetObj = obj => Object.keys(obj).forEach(k => (obj[k] = ''))

onMounted(() => {
  loadClass()
  loadAllAuthors()
  loadList()
})

const loadClass = () => {
  classList().then(res => {
    classListData.value = res.data || []
  })
}


const loadList = () => {
  const params = {
    pageNo: pageNo.value,
    pageSize: pageSize.value,
    ...searchParams.value
  }
  Object.keys(params).forEach(k => params[k] === '' && delete params[k])

  blogListData.value = []

  blogList(params).then(res => {
    if (res.success) {
      total.value = res.data.count
      blogListData.value = res.data.records || []
    }
  })
}

const loadAllAuthors = () => {
  blogList({ pageNo: 1, pageSize: 9999 }).then(res => {
    const map = new Map()
    res.data.records.forEach(r => map.set(r.authorid, { id: r.authorid, username: r.authorname }))
    userListData.value = Array.from(map.values())
  })
}

const handleSearch = () => {
  pageNo.value = 1
  loadList()
}
const resetSearch = () => {
  resetObj(searchParams.value)
  handleSearch()
}

const openAdd = () => {
  isEdit.value = false
  resetObj(formModel.value)
  formModel.value.isfeatured = 0
  formModel.value.iscommentable = 1
  drawerVisible.value = true
}
const openEdit = row => {
  isEdit.value = true
  Object.assign(formModel.value, row)
  drawerVisible.value = true
}

const handleDelete = id => {
  ElMessageBox.confirm('确认删除？', '提示', { type: 'warning' })
    .then(() => deleteBlog({ id }))
    .then(res => {
      ElMessage.success(res.message || '删除成功')
      loadList()
    })
}

const handleSubmit = async () => {
  await formRef.value.validate()

  // 深拷贝，避免污染原表单
  const data = { ...formModel.value }

  // 关键：Date → 字符串
  if (data.publishedat) {
    data.publishedat = dayjs(data.publishedat).format('YYYY-MM-DD HH:mm:ss')
  }

  const api = isEdit.value ? updateBlog : insertBlog
  api(data).then(res => {
    if (res.success) {
      ElMessage.success(res.message || '操作成功')
      drawerVisible.value = false
      loadList()
    }
  })
}

const handleSizeChange = val => {
  pageSize.value = val
  pageNo.value = 1
  loadList()
}
const handleCurrentChange = val => {
  pageNo.value = val
  loadList()
}

const handleAvatarSuccess = (res, file) => {
  formModel.value.coverimage = res.message
}
const beforeAvatarUpload = rawFile => {
  if (!rawFile.type.startsWith('image/')) {
    ElMessage.error('请上传图片')
    return false
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能大于 2MB')
    return false
  }
  return true
}

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入正文', trigger: 'blur' }],
  excerpt: [{ required: true, message: '请输入摘要', trigger: 'blur' }],
  coverimage: [{ required: true, message: '请上传封面', trigger: 'change' }],
  classid: [{ required: true, message: '请选择分类', trigger: 'change' }],
  authorid: [{ required: true, message: '请输入作者ID', trigger: 'blur' }],
  publishedat: [{ required: true, message: '请选择发布时间', trigger: 'change' }]
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>博客管理</span>
        <el-button type="primary" :icon="Plus" @click="openAdd">新增博客</el-button>
      </div>
    </template>

    <el-form inline>
      <el-form-item label="文章标题">
        <el-input v-model="searchParams.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="分类" prop="classname">
          <el-select v-model="searchParams.classid" placeholder="请选择分类" prop="classid" clearable style="width: 150px">
            <el-option v-for="c in classListData" :key="c.id" :label="c.name" :value="c.id" />
          </el-select>
        </el-form-item>
      <el-form-item label="置顶">
        <el-select v-model="searchParams.isfeatured" placeholder="是否置顶" clearable style="width: 150px">
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="评论">
        <el-select v-model="searchParams.iscommentable" placeholder="是否允许评论" clearable style="width: 150px">
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="blogListData" style="width: 100%" stripe>
      <el-table-column label="ID" prop="id" width="60" />
      <el-table-column label="文章标题" prop="title" show-overflow-tooltip width="130" />
      <el-table-column label="分类" prop="classname" width="120" />
      <el-table-column label="作者" prop="authorname" width="120" /> 
      <el-table-column label="文章摘要" prop="excerpt" show-overflow-tooltip />
      <el-table-column label="置顶" width="70">
        
        <template #default="{ row }">
          <el-tag :type="row.isfeatured === 1 ? 'success' : 'info'">
            {{ row.isfeatured === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="允许评论" width="100">
        
        <template #default="{ row }">
          <el-tag :type="row.iscommentable === 1 ? 'success' : 'info'">
            {{ row.iscommentable === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" prop="publishedat" width="160" />
      <el-table-column label="封面" width="180">
        <template #default="{ row }">
          <el-image
            v-if="row.coverimage"
            :src="`/api/file/download.do?filename=${row.coverimage}`"
            style="width: 100px; height: 60px"
            fit="cover"
          />
          <span v-else>无图</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button :icon="Edit" circle type="primary" @click="openEdit(row)" />
          <el-button :icon="Delete" circle type="danger" @click="handleDelete(row.id)" />
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="暂无数据" />
      </template>
    </el-table>

    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />

    <el-drawer v-model="drawerVisible" :title="isEdit ? '编辑博客' : '新增博客'" direction="rtl" size="480">
      <el-form ref="formRef" :model="formModel" :rules="rules" label-position="top">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formModel.title" />
        </el-form-item>
        <el-form-item label="正文" prop="content">
          <el-input v-model="formModel.content" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="文章摘要" prop="excerpt">
          <el-input v-model="formModel.excerpt" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="分类" prop="classname">
          <el-select v-model="formModel.classname" clearable>
            <el-option v-for="c in classListData" :key="c.id" :label="c.name" :value="c.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="作者" prop="authorname">
          <el-select v-model="formModel.authorname" clearable>
            <el-option v-for="u in userListData" :key="u.id" :label="u.username" :value="u.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="是否置顶" prop="isfeatured">
          <el-select v-model="formModel.isfeatured">
            <el-option label="置顶" :value="1" />
            <el-option label="普通" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="允许评论" prop="iscommentable">
          <el-select v-model="formModel.iscommentable">
            <el-option label="允许" :value="1" />
            <el-option label="禁止" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="publishedat">
          <el-date-picker
            v-model="formModel.publishedat"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择发布时间"
          />
        </el-form-item>
        <el-form-item label="封面图" prop="coverimage">
          <el-upload
            class="avatar-uploader"
            action="/api/file/upload.do"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="formModel.coverimage"
              :src="`/api/file/download.do?filename=${formModel.coverimage}`"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="SEO 标题" prop="metatitle">
          <el-input v-model="formModel.metatitle" />
        </el-form-item>
        <el-form-item label="SEO 描述" prop="metadescription">
          <el-input v-model="formModel.metadescription" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="SEO 关键词" prop="metakeywords">
          <el-input v-model="formModel.metakeywords" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div style="text-align: right">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </el-card>
</template>

<style scoped>
:root {
  --macaron-pink: #ff9db0;
  --macaron-mint: #a5e6ba;
  --macaron-blue: #8fd3f4;
  --macaron-yellow: #ffe66d;
  --macaron-purple: #d9b8ff;
  --macaron-bg: #fafafa;
  --macaron-card: #ffffff;
}

.page-container {
  min-height: 100%;
  box-sizing: border-box;
  background: linear-gradient(135deg, var(--macaron-bg), #f0f9ff);
  padding: 24px;
  border-radius: 20px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.header span {
  font-size: 22px;
  font-weight: 700;
  color: var(--macaron-blue);
}

.el-button--primary {
  background: var(--macaron-pink);
  border: none;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(255, 157, 176, 0.3);
}

.el-table {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.el-table th {
  background: var(--macaron-mint) !important;
  color: #fff;
  font-weight: 600;
}

.el-tag--success {
  background: var(--macaron-yellow);
  color: #5c3c00;
}

.el-pagination {
  margin-top: 24px;
  justify-content: center;
}

.el-drawer {
  border-radius: 24px 0 0 24px;
}

.el-form-item__label {
  font-weight: 600;
  color: var(--macaron-blue);
}

.el-input,
.el-textarea,
.el-input-number {
  border-radius: 12px;
}

.avatar-uploader .avatar {
  width: 160px;
  height: 160px;
  border-radius: 16px;
  object-fit: cover;
}

.el-table {
  font-size: 16px;          /* 内容字号 */
  line-height: 1.6;
}
.el-table th {
  font-size: 17px;          /* 表头字号 */
  font-weight: 700;
}
.el-table .cell {
  padding: 12px 8px;        /* 增加内边距，防止拥挤 */
}

.avatar-uploader-icon {
  font-size: 48px;
  color: var(--macaron-purple);
}
</style>